package com.wlq.demo.uitls;

import cn.hutool.core.util.StrUtil;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentFormat;

import java.io.*;
import java.net.ConnectException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author csb
 * @description: TODO
 * @date 2023/3/17 10:38
 */
public class FileConversionUtil {

    private static final Logger log = LoggerFactory.getLogger(FileConversionUtil.class);

    //启动OpenOffice服务
    static {
        List<String> command = new ArrayList<>();
        //OpenOffice的安装目录下的soffice路径C:\Program Files (x86)\OpenOffice 4\program\soffice.exe
        command.add("C:\\Program Files (x86)\\OpenOffice 4\\program\\soffice.exe");
        command.add("-headless");
        command.add("-accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard");
        command.add("-nofirststartwizard");
        command.forEach(v -> System.out.print(v + " "));
        System.out.println();
        ProcessBuilder builder = new ProcessBuilder();
        //正常信息和错误信息合并输出
        builder.redirectErrorStream(true);
        builder.command(command);
        //开始执行命令
        try {
            Process process = builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * office文件转换成pdf或html文件
     *
     *
     * @param file         要转换文件的路径，要包含名称和后缀（如：D:\GoogleDownload\中国地理复习笔记归纳总结(特细).doc）
     * @param saveFilePath 转换完后文件的保存路径(如：F:/test)
     * @param finalType    最终要转换为的文件的后缀传pdf或html （如：pdf）
     *
     * @return             返回最后转换后的文件名
     * @throws             IOException
     */
    public static String conversionPdfOrHtml(String file, String saveFilePath, String finalType) throws IOException {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String type = file.substring(file.lastIndexOf(".") + 1);
        return conversionPdfOrHtml(inputStream, saveFilePath, type, finalType);
    }


    /**
     * office文件转换成pdf或html文件
     *
     *
     * @param fromFileInputStream 要转换文件的文件流
     * @param saveFilePath        转换完后文件的保存路径(如：F:/test)
     * @param fileType            原始文件的后缀（如：doc）
     * @param finalType           最终要转换为的文件的后缀 （如：pdf）
     *
     * @return                    返回最后转换后的文件名
     * @throws                    IOException
     */
    public static String conversionPdfOrHtml(InputStream fromFileInputStream, String saveFilePath, String fileType, String finalType) throws IOException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timesuffix = sdf.format(date);

        finalType = "." + finalType;
        String fileTypes = "." + fileType;
        String head = fileType + "_";

        String docFileName = head + timesuffix + fileTypes;
        String resultFileName = head + timesuffix + finalType;

        //如果saveFilePath路径下有同名的原始文件和转化后的文件则删除。然后在saveFilePath下创建空的原始文件和转化后的文件
        File resultOutputFile = new File(saveFilePath + File.separatorChar + resultFileName);
        File docInputFile = new File(saveFilePath + File.separatorChar + docFileName);
        if (resultOutputFile.exists()) {
            resultOutputFile.delete();
        }
        if (docInputFile.exists()) {
            docInputFile.delete();
        }
        resultOutputFile.createNewFile();
        docInputFile.createNewFile();
        //将待转文件拷贝一份写入到saveFilePath下创建的空原始文件里
        try {
            OutputStream os = new FileOutputStream(docInputFile);
            int bytesRead = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fromFileInputStream.close();
        } catch (IOException e) {
        }

        //连接OpenOffice服务。需提前开启OpenOffice服务，否则会报错。参考https://www.cnblogs.com/of-course/p/10064874.html
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
        try {
            connection.connect();
        } catch (Exception e) {
            System.out.println("连接OpenOffice服务失败，请检查是否启动OpenOffice服务");
        }
        // 转化，saveFilePath下的拷贝的原始文件转化为pdf
        System.out.println("转换中......");
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
        converter.convert(docInputFile, resultOutputFile);

        qq(resultOutputFile);

        ww(resultOutputFile);


        connection.disconnect();
        //转换完之后删除拷贝的原始文件
        docInputFile.delete();
        return resultFileName;
    }

    public static void qq(File fleInput) throws IOException {
        FileInputStream fis=new FileInputStream(fleInput);
        InputStreamReader fsr=new InputStreamReader(fis,"utf-8");
        BufferedReader br=new BufferedReader(fsr);

        int intAlpha,intNum,intOther,intChinese;

        intAlpha=intNum=intOther=intChinese=0;
        int intChar=br.read();
        while (intChar!=-1){
            if ((intChar>=0x41 && intChar<=0x5A) || (intChar>=0x61&& intChar<=0x7A)){
                intAlpha++;
            }else if (intChar>=0x30 && intChar<=0x39){
                intNum++;
            }else if (intChar>=0 && intChar<=127)
            {
                intOther++;
            }else{
                intChinese++;
            }
            intChar=br.read();
        }

        fis.close();

        System.out.println("Alpha count=" + intAlpha);
        System.out.println("Number count=" + intNum);
        System.out.println("Other count=" + intOther);
        System.out.println("Chinese count=" + intChinese);
    }

    public static void ww(File file){
        int charnum=0;//字符数
        int x=-1;
        FileReader fReader = null;
        try {
            fReader = new FileReader(file);
            while((x=fReader.read())!=-1){//按字符读文件，判断，符合则字符加一
                char a=(char)x;
                if(a!='\n'&&a!='\r'){
                    charnum++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fReader != null){
                try {
                    fReader.close();//关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("count=" + charnum);
    }

    public static int office2PDF(String sourceFile, String destFile) {
        if(StrUtil.isEmpty(sourceFile) || StrUtil.isEmpty(destFile) ){
            log.debug("文件路径为空");
            return -1;
        }
        log.debug("sourceFile===========" + sourceFile);
        log.debug("destFile===========" + destFile);

        try {
            File inputFile = new File(sourceFile);
            if (!inputFile.exists()) {
                log.debug("没有文档===========");
                return -1;// 找不到源文件, 则返回-1
            }
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            // 文件输入输出流
            FileInputStream in = null;
            FileOutputStream out = null;
            in = new FileInputStream(inputFile);
            out = new FileOutputStream(outputFile);

            if(in == null){
                log.debug("文件输入流为空===========");
                return -1;
            }
            if(out == null){
                log.debug("文件输出流为空===========");
                return -1;
            }
            // 创建连接
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);

            //OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();

            // 创建转换器
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            // 文件格式
            DefaultDocumentFormatRegistry factory = new DefaultDocumentFormatRegistry();


            // 待转换文件名称及扩展名称
            String officeName = inputFile.getName();
            String officeExt = officeName.substring(officeName.lastIndexOf(".") + 1);
            // 待转换文件 转换文件格式对象

            // todo docx先转doc再转pdf ,否则格式会错乱
            if (officeExt.equals("docx") || officeExt.equals("DOCX")){

            }

            DocumentFormat officeFormat = factory.getFormatByFileExtension(officeExt);
            DocumentFormat pdfFormat = factory.getFormatByFileExtension("pdf");
            log.debug("开始将word转为PDF===========");

            // 记录转换时间 咨询转换
            long startTime = System.currentTimeMillis();
            converter.convert(in, officeFormat, out, pdfFormat);
//            converter.convert(in, out);
            long endTime = System.currentTimeMillis();
            log.debug("转换时间：" + (endTime - startTime) + "ms");

            //断开连接
            connection.disconnect();
            return 0;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.debug("FileNotFoundException===========" + e.getMessage() );
            return -1;
        } catch (IOException e) {
            e.printStackTrace();
            log.debug("IOException===========" + e.getMessage());

            return -1;
        } catch (Exception e){
            e.printStackTrace();
            log.debug("Exception===========" + e.getMessage());
            return -1;
        }
//        return 1;
    }

}
